<template>
  <div class="container">
    <div class="app-container">
      <el-tree :expand-on-click-node="false" default-expand-all :data="depts" :props="defaultProps">
        <!-- 节点结构 -->
        <!-- v-slot="{ node, data }" 只能作用在template -->
        <template v-slot="{ data }">
          <el-row style="width:100%;height:40px" type="flex" justify="space-between" align="middle">
            <el-col>{{ data.name }}</el-col>
            <el-col :span="4">
              <span class="tree-manager">{{ data.managerName }}</span>
              <!-- $event 实参 表示类型 -->
              <el-dropdown @command="operateDept($event, data.id)">
                <!-- 显示区域内容 -->
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <!-- 下拉菜单选项 -->
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <!-- 对话框 -->
    <el-dialog :title="addForm.id? '编辑部门' :'新增部门'" :visible="showDialog" @close="close">
      <el-form ref="addForm" label-width="120px" :model="addForm" :rules="addRules">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="addForm.name" placeholder="1-50个字符" style="width: 80%" size="mini" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="addForm.code" placeholder="1-50个字符" style="width: 80%" size="mini" />
        </el-form-item>
        <el-form-item label="部门负责人" prop="managerId">
          <el-select v-model="addForm.managerId" placeholder="请选择负责人" style="width: 80%" size="mini">
            <el-option
              v-for="item in manager"
              :key="item.id"
              :label="item.username"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input
            v-model="addForm.introduce"
            placeholder="1-300个字符"
            type="textarea"
            size="mini"
            :rows="4"
            style="width: 80%"
          />
        </el-form-item>
        <el-form-item>
          <!-- 按钮 -->
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button size="mini" type="primary" @click="confirmAdd">确定</el-button>
              <el-button size="mini" @click="showDialog = false">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDepartment, getManagerList, addDepartment, getDepartmentDetail, updateDepartment, delDepartment } from '@/api/department'

import { transListToTreeData } from '@/utils/index'
export default {
  name: 'Department',
  data() {
    return {
      depts: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      currentNodeId: null, // 存储当前点击的id
      showDialog: false,
      // 部门负责人列表
      manager: [],
      // 表单
      addForm: {
        name: '',
        code: '',
        managerId: '',
        introduce: ''

      },
      // 表单校验
      addRules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称长度1-50个字符', trigger: 'blur' },
          {
            trigger: 'blur',
            validator: async(rule, value, callback) => {
              const result = await getDepartment()
              if (result.some(item => item.name === value)) {
                callback(new Error('部门中已经有该名称'))
              } else {
                callback()
              }
            }
          }
        ],
        code: [
          { required: true, message: '部门编号不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编号长度1-50个字符', trigger: 'blur' },
          {
            trigger: 'blur',
            validator: async(rule, value, callback) => {
              const result = await getDepartment()
              if (result.some(item => item.code === value)) {
                callback(new Error('部门中已经有该编号'))
              } else {
                callback()
              }
            }

          }
        ],
        managerId: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍长度1-300个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    // 获取组织架构数据
    async getDepartment() {
      const res = await getDepartment()
      this.depts = transListToTreeData(res, 0)
    },
    async operateDept(type, id) {
      console.log(type, id)
      const res = await getManagerList()
      console.log(res)
      this.manager = res
      // 添加子部门
      if (type === 'add') {
        this.showDialog = true
        this.currentNodeId = id
      } else if (type === 'edit') {
        this.showDialog = true
        this.currentNodeId = id
        this.edit()
      } else if (type === 'del') {
        this.$confirm('你确定要删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          await delDepartment(id)
          this.getDepartment()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }).catch(() => {
        })
      }
    },
    // 清空表单
    close() {
      this.$refs.addForm.resetFields()
      this.showDialog = false
      this.addForm = {
        name: '',
        code: '',
        managerId: '',
        introduce: ''
      }
      this.currentNodeId = ''
    },
    // 创建
    async confirmAdd() {
      await this.$refs.addForm.validate()
      if (this.addForm.id) {
        await updateDepartment(this.addForm)
        this.$message.success('更新成功')
      } else {
        await addDepartment({ ...this.addForm, pid: this.currentNodeId })
        this.$message.success('创建成功')
      }

      this.close()
      this.getDepartment()
    },
    // 编辑
    async edit() {
      const res = await getDepartmentDetail(this.currentNodeId)
      console.log(res)
      const {
        name,
        code,
        managerId,
        introduce,
        id
      } = res
      this.addForm = {
        name,
        code,
        managerId,
        introduce,
        id
      }
    }

  }
}
</script>

<style   scoped>
.app-container {
  padding: 30px 140px;
  font-size: 14px;
}

.tree-manager {
  width: 50px;
  display: inline-block;
  margin: 10px;
}

::v-deep.tree-manager {
  width: 70px;
}

/* .form-container {
  padding: 0px 80px;
} */
/* /* ::v-deep.el-input__inner {
  height: 0px;
} */
</style>
